
var board_state = 'news_list';
function draw_board() {
    document.querySelector('.news-board-content .news-board-first').style['display'] = 'none';
    document.querySelector('.news-board-content .news-board-second').style['display'] = 'none';
    document.querySelector('.news-board-content .news-board-third').style['display'] = 'none';
    document.querySelector('.news-board-content .news-board-fourth').style['display'] = 'none';
    switch (board_state) {
        case 'news_list':
            document.querySelector('.news-board-content .news-board-first').style['display'] = 'block';
            break;
        case 'news_detail':
            document.querySelector('.news-board-content .news-board-second').style['display'] = 'block';
            break;
        case 'news_edit':
            document.querySelector('.news-board-content .news-board-third').style['display'] = 'block';
            break;
        case 'news_add':
            document.querySelector('.news-board-content .news-board-fourth').style['display'] = 'block';
            break;
        default:
            document.querySelector('.news-board-content .news-board-first').style['display'] = 'block';
            break;
    }
}

let news_currentPage = 1;
let news_currentIndex = 1;
var news_list_pages = 0;
const itemsPerPage = 10;
let news_list = [];
const news_jump_page_input = document.querySelector('.news-board-content .news-board-first #jump-page input');

news_jump_page_input.addEventListener('keydown', function (event) {
    if (event.key == 'Enter') {
        update_news_list_page();
        // 如果输入的内容不是整数，则执行float_text("你输入的页码有误");
        if (!/^\d+$/.test(this.value)) {
            float_text("你输入的页码有误");
            this.value = '';
            return;
        }
        // 如果输入的内容不在 [1, news_list_pages] 范围内，则执行float_text("你输入的页码有误");
        if (this.value < 1 || this.value > news_list_pages) {
            float_text("你输入的页码有误");
            this.value = '';
            return;
        }
        // 接着往下执行具体的逻辑
        // ...
        news_currentPage = this.value;
        displayData(news_currentPage);
        update_news_list_page();
        this.blur();
    }
});

const fetchData = async () => {
    news_list = [];
    const getNewsApi = "http://47.109.78.200:10010/board/selectAll";
    var data = {
        pageNum: news_currentPage,
        pageSize: 10,
    }
    var news_board_fullUrl = getRequestUrl(data, getNewsApi);
    await fetchWithTimeout(news_board_fullUrl, {
        headers: {
            token: getCookieValue('token')
        }
    })
        .then(response => {
            return response.json();
        })
        .then(data => {
            if (data['code'] == 100) {
                news_list = data['data'];
                news_list_pages = Math.ceil(news_list.length / itemsPerPage);
                if (news_list_pages <= 0) {
                    news_currentPage = 0;
                }
                news_jump_page_input.value = news_currentPage;
                return;
            }
            if (data['code'] == 200) {
                if (data['msg'] == '未登录') {
                    exit_login();
                    return;
                }
            }
            float_text('获取公告出现异常');

        })
        .catch(error => {
            if (error == 'Error: timeout') {
                float_text('获取公告超时');
            } else {
                console.log(error);
                float_text('获取公告时出现未知错误');
            }
        });
};

async function update_news_list_page() {
    const api = 'http://47.109.78.200:10010/board/selectBoardCount';
    await fetchWithTimeout(api, {
        headers: {
            token: getCookieValue('token')
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data['msg'] == '用户未登入') {
                exit_login();
                return;
            }
            news_list_pages = Math.ceil((data['data'] || 0) / itemsPerPage);
            document.querySelector('.news-board-content .news-board-first #jump-page .page-num').innerHTML = `/ ${news_list_pages}`;
        })
        .catch(error => {
            console.log(error);
        });
}

async function displayData() {
    await fetchData();
    const displayList = news_list;

    let tableRows = "";
    for (const item of displayList) {
        tableRows += `
          <tr>
            <td>${item.id}</td>
            <td id='news-title'>${item.topic}</td>
            <td>${item.time}</td>
            <td>
                <div id='edit-button' class='operate-button icon-bianji1'></div>
                <div id='delete-button' class='operate-button icon-shanchu'></div>
            </td>
          </tr>
        `;
    }
    document.querySelector('.news-table #table-body').innerHTML = tableRows;
    var all_element = document.querySelectorAll('.news-table #table-body #news-title');
    for (var i = 0; i < all_element.length; i++) {
        all_element[i].setAttribute('index', i);
        all_element[i].addEventListener('click', function () {
            var index = this.getAttribute('index');
            news_currentIndex = index;
            document.querySelector('.news-board-content .news-board-first').style['display'] = 'none';
            document.querySelector('.news-board-content .news-board-second').style['display'] = 'block';
            document.querySelector('.news-board-content .news-board-second #news-detail').innerHTML = `
                    <p class="news-title">${news_list[index].topic}</p>
                    <p class="news-time">${news_list[index].time}</p>
                    <p class="news-text">${news_list[index].content}</p>
                `;
        });
    }
    //编辑
    all_element = document.querySelectorAll('.news-table #table-body #edit-button');
    for (var i = 0; i < all_element.length; i++) {
        all_element[i].setAttribute('index', i);
        add_float_tip(all_element[i], '编辑');
        all_element[i].addEventListener('click', function () {
            var index = this.getAttribute('index');
            board_state = 'news_edit';
            document.querySelector('.news-board-content .news-board-third').innerHTML = `
                <div style="display: flex; margin: 20px 0;">
                    <div class="info-show">ID :</div>
                    <input readonly id='id-input' class='muti-line-input' type="text"
                        style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                </div>
                <div style="display: flex; margin: 20px 0;">
                    <div class="info-show">标题 :</div>
                    <input id='title-input' class='muti-line-input' type="text"
                        style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                </div>
                <div style="display: flex; margin: 20px 0;">
                    <div class="info-show">正文 :</div>
                    <textarea id='text-input' class='muti-line-input' type="text"
                        style="display: inline-block;word-break:break-all; margin: 0 30px;font-size: 22px; width: 75%; height: 300px;"></textarea>
                </div>
                <div>
                    <div id="cancel-edit-news" class="rect_button icon-guifandaohanglancha"></div>
                    <div id="commit-edit-news" class="rect_button icon-zhengque"></div>
                </div>
                `;
            document.querySelector(".news-board-content .news-board-third #cancel-edit-news").addEventListener("click",
                function () {
                    board_state = 'news_list';
                    draw_board();
                }
            );
            document.querySelector(".news-board-content .news-board-third #commit-edit-news").addEventListener("click",
                async function () {
                    const news_id_input = document.querySelector('.news-board-content .news-board-third #id-input');
                    const news_title_input = document.querySelector('.news-board-content .news-board-third #title-input');
                    const news_text_input = document.querySelector('.news-board-content .news-board-third #text-input');
                    const data = {
                        id: news_id_input.value,
                        topic: news_title_input.value,
                        content: news_text_input.value,
                        userId: getCookieValue('login_userId'),
                    };
                    const api = 'http://47.109.78.200:10010/board/update';
                    // const url = getRequestUrl(data, api);
                    await fetchWithTimeout(api, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            token: getCookieValue('token'),
                        },
                        body: JSON.stringify(data),
                    }).then(response => response.json())
                        .then(data => {
                            if (data['code'] == 100) {
                                float_text('更新成功');
                            } else {
                                float_text('更新失败');
                            }
                            if (data['msg'] == '用户未登入') {
                                exit_login();
                                return;
                            }
                        }).catch(error => {
                            console.log(error);
                        })
                    float_text('修改成功');
                    await displayData();
                    board_state = 'news_list';
                    draw_board();
                }
            );

            add_float_tip(document.querySelector(".news-board-content .news-board-third #cancel-edit-news"), "取消编辑");
            add_float_tip(document.querySelector(".news-board-content .news-board-third #commit-edit-news"), "确认修改");
            draw_board();
            const news_id = news_list[index].id;
            const news_title = news_list[index].topic;
            const news_text = news_list[index].content;
            const news_id_input = document.querySelector('.news-board-content .news-board-third #id-input');
            const news_title_input = document.querySelector('.news-board-content .news-board-third #title-input');
            const news_organization_input = document.querySelector('.news-board-content .news-board-third #organization-input');
            const news_text_input = document.querySelector('.news-board-content .news-board-third #text-input');
            news_id_input.value = news_id;
            news_title_input.value = news_title;
            news_text_input.value = news_text;
        });
    }
    //删除
    all_element = document.querySelectorAll('.news-table #table-body #delete-button');
    for (var i = 0; i < all_element.length; i++) {
        all_element[i].setAttribute('index', i);
        add_float_tip(all_element[i], '删除');
        all_element[i].addEventListener('click', function () {
            var index = this.getAttribute('index');
            showFullScreenTip(
                `
                    <div style="background-color: #fff; padding: 20px 30px; font-size:26px; font-weight: lighter; border:none; border-radius:20px; overflow:hidden;">
                        <div style="margin: 0px 20px 40px 20px; color:rgb(0,0,0); font-weight: bold;">确认删除?</div>
                        <p style="margin: 10px 60px; font-size:22px;">ID : ${news_list[index].id}</p>
                        <p style="margin: 10px 60px; font-size:22px;">标题 : ${news_list[index].topic}</p>
                        <p style="margin: 10px 60px; font-size:22px;">时间 : ${news_list[index].time}</p>
                        <button class='fullScreen-button' id="confirm-delete" index=${index} style="display:inline; width:90%; height:45px; margin: 30px 20px 0 20px; font-size:22px;">确认</button>
                        <button class='fullScreen-button2' style="display:inline; width:90%; height:45px; margin: 30px 20px 0 20px; font-size:22px;" onclick="hideFullScreenTip()">取消</button> 
                    </div>
                    `
            );
            document.querySelector(".fullScreen-tip #confirm-delete").addEventListener('click',
                async function () {
                    var index = this.getAttribute('index');
                    var id = news_list[index].id;
                    //删除公告...
                    const api = 'http://47.109.78.200:10010/board/delete';
                    data = {
                        boardId: id,
                    };
                    const url = getRequestUrl(data, api);
                    fetchWithTimeout(url, {
                        method: 'delete',
                        headers: {
                            'Content-Type': 'application/json',
                            'token': getCookieValue('token'),
                        }
                    }).then(response => response.json())
                        .then(data => {
                            if (data['code'] == 100) {
                                float_text('删除成功');
                            } else {
                                float_text('删除失败');
                            }
                            if (data['msg'] == '用户未登入') {
                                exit_login();
                                return;
                            }
                            displayData();
                        }).catch(error => {
                            console.log(error);
                        });
                    hideFullScreenTip();
                }
            );

        });
    }

    news_jump_page_input.value = news_currentPage;
};

document.querySelector(".news-board-content .news-board-first #prev-page").addEventListener("click",
    async function () {
        await update_news_list_page();
        if (news_currentPage > 1) {
            if (news_currentPage - 1 > news_list_pages) {
                news_currentPage = news_list_pages;
                float_text('云端数据已更新, 已为你跳转到合法页面');
            } else {
                news_currentPage--;
            }
            await displayData(news_currentPage);
        }
    }
);
document.querySelector(".news-board-content .news-board-first #next-page").addEventListener("click",
    async function () {
        await update_news_list_page();
        if (news_currentPage < news_list_pages) {
            news_currentPage++;
            await displayData(news_currentPage);
        }
    }
);

document.querySelector(".news-board-content .news-board-first #add-news").addEventListener('click',
    function () {
        board_state = 'news_add';
        draw_board();
        document.querySelector(".news-board-content .news-board-fourth").innerHTML = `
                <div style="display: flex; margin: 20px 0;">
                    <div class="info-show">标题 :</div>
                    <input id='title-input' class='muti-line-input' type="text"
                        style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                </div>
                <div style="display: flex; margin: 20px 0;">
                    <div class="info-show">正文 :</div>
                    <textarea id='text-input' class='muti-line-input' type="text"
                        style="display: inline-block;word-break:break-all; margin: 0 30px;font-size: 22px; width: 75%; height: 300px;"></textarea>
                </div>
                <div>
                    <div id="cancel-publish-news" class="rect_button icon-guifandaohanglancha"></div>
                    <div id="publish-news" class="rect_button icon-zhengque"></div>
                </div>
            `;
        const button1 = document.querySelector(".news-board-content .news-board-fourth #cancel-publish-news");
        const button2 = document.querySelector(".news-board-content .news-board-fourth #publish-news");
        button1.addEventListener('click',
            function () {
                board_state = 'news_list';
                draw_board();
            }
        );
        button2.addEventListener('click',
            async function () {
                const news_title_input = document.querySelector('.news-board-content .news-board-fourth #title-input');
                const news_organization_input = document.querySelector('.news-board-content .news-board-fourth #organization-input');
                const news_text_input = document.querySelector('.news-board-content .news-board-fourth #text-input');
                if (news_title_input.value == '') {
                    float_text('标题不可为空');
                    return;
                }
                if (news_text_input.value == '') {
                    float_text('正文不可为空');
                    return;
                }
                //发布公告...
                const api = 'http://47.109.78.200:10010/board/insertBoard';
                data = {
                    topic: news_title_input.value,
                    content: news_text_input.value,
                    userId: getCookieValue('login_userId'),
                }
                await fetchWithTimeout(api, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': getCookieValue('token'),
                    },
                    body: JSON.stringify(data)
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data['code'] == 100) {
                            float_text('发布成功');
                        } else {
                            float_text('发布失败');
                        }
                        if (data['msg'] == '用户未登入') {
                            exit_login();
                            return;
                        }
                    }).catch(error => {
                        float_text('发布公告出现异常...');
                    });

                board_state = 'news_list';
                draw_board();
                displayData();
            }
        );
        add_float_tip(button1, '取消发布');
        add_float_tip(button2, '确认发布');
    }
);

document.querySelector(".news-board-content .news-board-second #return-button").addEventListener("click",
    function () {
        board_state = 'news_list';
        draw_board();
    }
);

document.querySelector(".news-board-content .news-board-second #prev-page").addEventListener("click",
    async function () {
        if (news_currentIndex <= 0 && news_currentPage > 0) {
            float_text("没有上一篇了");
        } else {
            news_currentIndex--;
            if (news_currentIndex < 0) {
                news_currentPage--;
                news_currentIndex = 9;
                await displayData();
            }
            document.querySelector('.news-board-content .news-board-second #news-detail').innerHTML = `
                    <p class="news-title">${news_list[news_currentIndex].topic}</p>
                    <p class="news-time">${news_list[news_currentIndex].time}</p>
                    <p class="news-text">${news_list[news_currentIndex].content}</p>
                `;
        }
    }
);
document.querySelector(".news-board-content .news-board-second #next-page").addEventListener("click",
    async function () {
        if (news_currentIndex >= news_list.length - 1 && news_currentPage >= news_list_pages) {
            float_text("没有下一篇了");
        } else {
            news_currentIndex++;
            if (news_currentIndex >= 9) {
                news_currentPage++;
                news_currentIndex = 0;
                await displayData();
            }
            document.querySelector('.news-board-content .news-board-second #news-detail').innerHTML = `
                    <p class="news-title">${news_list[news_currentIndex].topic}</p>
                    <p class="news-time">${news_list[news_currentIndex].time}</p>
                    <p class="news-text">${news_list[news_currentIndex].content}</p>
                `;
        }
    }
);

async function board_init() {
    news_currentPage = 1;
    news_currentIndex = 1;
    board_state = 'news_list';
    draw_board();
    float_text('正在加载公告...');
    await update_news_list_page();
    await displayData();
}
board_init();